package com.itjin.resume_back.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itjin.resume_back.entity.Resume;
import com.itjin.resume_back.mapper.ResumeMapper;
import com.itjin.resume_back.service.ResumeService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
public class ResumeServiceImpl extends ServiceImpl<ResumeMapper, Resume> implements ResumeService {

  @Value("${file.upload-dir}")
  private String uploadDir;

  private final ObjectMapper objectMapper = new ObjectMapper();

  @Override
  public void uploadResume(Long userId, String title, String description, MultipartFile file, String tags) {
    try {
      // 创建上传目录
      Path uploadPath = Paths.get(uploadDir);
      if (!Files.exists(uploadPath)) {
        Files.createDirectories(uploadPath);
      }

      // 生成文件名
      String originalFilename = file.getOriginalFilename();
      String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
      String fileName = UUID.randomUUID().toString() + extension;

      // 验证文件
      if (file.isEmpty()) {
        throw new IOException("文件为空");
      }

      // 保存文件
      Path filePath = uploadPath.resolve(fileName);
      Files.copy(file.getInputStream(), filePath);

      // 处理tags，确保是有效的JSON格式
      String jsonTags = null;
      if (tags != null && !tags.trim().isEmpty()) {
        // 将逗号分隔的标签转换为JSON数组
        List<String> tagList = Arrays.asList(tags.split(","));
        jsonTags = objectMapper.writeValueAsString(tagList);
      }

      // 保存简历信息
      Resume resume = new Resume();
      resume.setUserId(userId);
      resume.setTitle(title);
      resume.setDescription(description);
      resume.setFileUrl(fileName);
      resume.setTags(jsonTags);
      save(resume);
    } catch (IOException e) {
      throw new RuntimeException("文件上传失败", e);
    }
  }

  @Override
  public void updateResume(Long id, String title, String description, MultipartFile file, String tags) {
    Resume resume = getById(id);
    if (resume == null) {
      throw new RuntimeException("简历不存在");
    }

    try {
      if (file != null && !file.isEmpty()) {
        // 删除旧文件
        Path oldFilePath = Paths.get(uploadDir, resume.getFileUrl());
        Files.deleteIfExists(oldFilePath);

        // 生成新文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + extension;

        // 保存新文件
        Path newFilePath = Paths.get(uploadDir, fileName);
        Files.copy(file.getInputStream(), newFilePath);

        resume.setFileUrl(fileName);
      }

      // 处理tags，确保是有效的JSON格式
      String jsonTags = null;
      if (tags != null && !tags.trim().isEmpty()) {
        // 将逗号分隔的标签转换为JSON数组
        List<String> tagList = Arrays.asList(tags.split(","));
        jsonTags = objectMapper.writeValueAsString(tagList);
      }

      resume.setTitle(title);
      resume.setDescription(description);
      resume.setTags(jsonTags);
      updateById(resume);
    } catch (IOException e) {
      throw new RuntimeException("文件更新失败", e);
    }
  }

  @Override
  public void approveResume(Long id, Integer status) {
    Resume resume = getById(id);
    if (resume == null) {
      throw new RuntimeException("简历不存在");
    }

    resume.setIsApproved(status);
    updateById(resume);
  }

  @Override
  public void deleteResume(Long id) {
    Resume resume = getById(id);
    if (resume == null) {
      throw new RuntimeException("简历不存在");
    }

    try {
      // 删除文件
      Path filePath = Paths.get(uploadDir, resume.getFileUrl());
      Files.deleteIfExists(filePath);
    } catch (IOException e) {
      throw new RuntimeException("文件删除失败", e);
    }

    removeById(id);
  }

  @Override
  public byte[] getResumeFile(Long id) {
    Resume resume = getById(id);
    if (resume == null) {
      throw new RuntimeException("简历不存在");
    }

    try {
      Path filePath = Paths.get(uploadDir, resume.getFileUrl());
      return Files.readAllBytes(filePath);
    } catch (IOException e) {
      throw new RuntimeException("文件读取失败", e);
    }
  }
}